package com.source.multithread.download;

import java.util.concurrent.CountDownLatch;

public class Main {
    //等待2个子线程执行完毕，计数器为2
    static CountDownLatch countDownLatch = new CountDownLatch(4);

    public static void main(String[] args) {
        System.out.println("start subThread doing...");
        //创建并开启2个子线程
        SubThread subThread1 = new SubThread();
        SubThread subThread2 = new SubThread();
        SubThread subThread3 = new SubThread();
        SubThread subThread4 = new SubThread();
        subThread1.start();
        subThread2.start();
        subThread3.start();
        subThread4.start();

        try {
            //阻塞主线程，等待子线程结束
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("subThread are finish...");
    }

    static class SubThread extends Thread {
        @Override
        public void run() {
            //模拟执行任务
            try {
                sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //子线程执行完毕，减少计数器
            System.out.println(getName() + " done...");
            countDownLatch.countDown();
        }
    }
}